package com.founder.creater.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;

public class DigestUtils {

	/**
	 * 适用于上G大的文件
	 * @throws FileNotFoundException 
	 */
	public static String getFileSha1(File file) {
		FileInputStream in = null;
		MessageDigest messagedigest;
		try {
			in = new FileInputStream(file);
			messagedigest = MessageDigest.getInstance("SHA-1");

			byte[] buffer = new byte[1024 * 1024 * 10];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				// 该对象通过使用 update（）方法处理数据
				messagedigest.update(buffer, 0, len);
			}

			// 对于给定数量的更新数据，digest 方法只能被调用一次。在调用 digest 之后，MessageDigest
			// 对象被重新设置成其初始状态。
			return byte2hex(messagedigest.digest());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(null != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	/** 
     * byte数组转hex字符串<br/> 
     * 一个byte转为2个hex字符 
     * @param src 
     * @return 
     */  
    public static String byte2hex(byte[] src){         
        char[] res = new char[src.length*2];    
        final char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};    
        for(int i=0,j=0; i<src.length; i++){    
            res[j++] = hexDigits[src[i] >>>4 & 0x0f];    
            res[j++] = hexDigits[src[i] & 0x0f];    
        }    
            
        return new String(res);    
    }
    
    public static String toHex(byte b) {  
        String result = Integer.toHexString(b & 0xFF);  
        if (result.length() == 1) {  
            result = '0' + result;  
        }  
        return result;  
    }
}
